package com.eques.demo.lock

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import com.eques.base.BaseActivity
import com.eques.database.dao.DevListDao
import com.eques.demo.AlarmRecordListActivity
import com.eques.demo.LockMessageListActivity
import com.eques.demo.R
import com.eques.demo.RingRecordListActivity
import com.eques.demo.VideoCallActivity
import com.eques.event.EventTotalThread
import com.eques.https.ShaowUtils
import com.eques.icvss.utils.ELog
import com.eques.service.DoorBellService
import com.eques.util.BaseAppApplication
import com.eques.util.Config
import com.eques.util.DateTimeUtil
import com.eques.util.HttpUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.Date

/**
 * 锁主页
 */
class MainLockActivity : BaseActivity() {
    private lateinit var tv_state: TextView
    private lateinit var tv_setting: TextView
    private lateinit var tv_ring: TextView
    private lateinit var tv_alarm: TextView
    private lateinit var tv_msg: TextView
    private lateinit var btn_video: Button
    private lateinit var btn_ring: Button
    private lateinit var btn_lock_alarm: Button

    private lateinit var btn_lock_msg: Button

    private var devId: String? = null
    private val REQUEST_METHOD_PIR = "get_device_alarm"
    private val REQUEST_METHOD_VISITOR = "get_device_ring"
    private var startTime: String? = null
    private var endTime: String? = null
    private var startAndEndDate: Date? = null

    private lateinit var devDao: DevListDao
    private lateinit var userName: String

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main_lock)
        EventBus.getDefault().register(this)
        devId = intent.getStringExtra("devId")
        userName = preference.getString(Config.EQUES_USER_NAME)!!
        initView()
        initData()
    }

    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }

    @SuppressLint("NotifyDataSetChanged")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onRefreshEvent(event: EventTotalThread) {
        when (event.refresh) {
            Config.EVENT_DEVICE_LIST_REFRESH, Config.EVENT_BDY_LIST->{
               //更新设备状态
            }

            Config.EVENT_SHAOW_STATE -> {
                runOnUiThread {
                    tv_state.text = event.stringMsg
                }
            }

            Config.EVENT_SHAOW_SETTING -> {
                tv_setting.text = event.stringMsg
            }
        }
    }

    override fun initView() {
        tv_state = findViewById(R.id.tv_state)
        tv_setting = findViewById(R.id.tv_setting)
        tv_ring = findViewById(R.id.tv_ring)
        tv_alarm = findViewById(R.id.tv_alarm)
        tv_msg = findViewById(R.id.tv_msg)
        btn_video = findViewById(R.id.btn_video)
        btn_ring = findViewById(R.id.btn_ring)
        btn_lock_alarm = findViewById(R.id.btn_lock_alarm)
        btn_lock_msg = findViewById(R.id.btn_lock_msg)
        btn_lock_alarm.setOnClickListener {
            val intent = Intent(this, AlarmRecordListActivity::class.java)
            intent.putExtra("devId", devId)
            startActivity(intent)
        }
        btn_lock_msg.setOnClickListener {
            val intent = Intent(this, LockMessageListActivity::class.java)
            intent.putExtra("devId", devId)
            startActivity(intent)
        }
        btn_ring.setOnClickListener {
            val intent = Intent(this, RingRecordListActivity::class.java)
            intent.putExtra("devId", devId)
            startActivity(intent)
        }
        btn_video.setOnClickListener {
            intoVideo()
        }
    }

    private fun intoVideo() {
        devDao = BaseAppApplication.Companion.instance!!.getYkDao(this)
        CoroutineScope(Dispatchers.IO).launch {
            val devList = devDao.getBdyListEntry(userName, devId!!)
            ELog.e("设备详细信息", devList)
            val state = devList.stat
            when (state) {
                0 -> {
                    runOnUiThread {
                        Toast.makeText(this@MainLockActivity, "设备已离线", Toast.LENGTH_SHORT).show()
                    }
                }
                1,2 -> {
                    runOnUiThread {
                    val intent = Intent(this@MainLockActivity, VideoCallActivity::class.java)
                    intent.putExtra("devId", devId)
                    startActivity(intent)
                    }
                }
//                2 -> {
//                    runOnUiThread {
//                        //可手动唤醒，或者通过指令唤醒
//                        Toast.makeText(this@MainLockActivity, "请先唤醒设备", Toast.LENGTH_SHORT).show()
//                    }
//                }

            }
        }
    }

    override fun initData() {
        //只查询到今天
        startAndEndDate = DateTimeUtil.getCurrDate()
        startTime = java.lang.String.valueOf(
            DateTimeUtil.getSpecifiedDateTime_000000(startAndEndDate).time
        )
        endTime = java.lang.String.valueOf(
            DateTimeUtil.getSpecifiedDateTime_235959(startAndEndDate).time
        )
        CoroutineScope(Dispatchers.IO).launch {
            ShaowUtils.getInstance(this@MainLockActivity).getSetting(devId!!)
            ShaowUtils.getInstance(this@MainLockActivity).getState(devId!!)
        }
        getRing()
        getAlarm()
        getLockMsg()
    }


    /**
     * 获取门铃记录
     */
    fun getRing() {
        var host = preference.getMainUrl()
        val token = preference.getString(Config.EQUES_USER_TOKEN)
        val uid = preference.getString(Config.EQUES_USER_UID)
        val url = Config.getVisitorMessageListUrl(
            host,
            REQUEST_METHOD_VISITOR,
            uid,
            token,
            devId,
            startTime,
            endTime,
            "0",
            "1000"
        )
        println("GET Ring url: $url")
        HttpUtil.getAsync(
            url = url.toString(),
        ) { result ->
            result.onSuccess { response ->
                println("GET Ring Response: $response")
                runOnUiThread {
                    tv_ring.text = response
                }

            }.onFailure { exception ->
                println("GET Ring Error: ${exception.message}")
            }
        }
    }

    /**
     * 获取报警记录
     */
    fun getAlarm() {
        var host = preference.getSubUrl()
        val token = preference.getString(Config.EQUES_USER_TOKEN)
        val uid = preference.getString(Config.EQUES_USER_UID)
        val url = Config.getE1ProOpenLockAlarmListUrl(
            host,
            uid,
            token,
            devId,
            startTime,
            endTime,
            "0",
            "1000"
        )
        println("GET Alarm url: $url")
        HttpUtil.getAsync(
            url = url.toString(),
        ) { result ->
            result.onSuccess { response ->
                println("GET Alarm Response: $response")
                runOnUiThread {
                    tv_alarm.text = response
                }

            }.onFailure { exception ->
                println("GET Error: ${exception.message}")
            }
        }
    }


    /**
     * 获取锁记录
     */
    fun getLockMsg() {
        val host = preference.getSubUrl()
        val token = preference.getString(Config.EQUES_USER_TOKEN)
        val uid = preference.getString(Config.EQUES_USER_UID)
        val url = Config.getE1ProOpenLockRecordListUrl(
            host,
            uid,
            token,
            devId,
            startTime,
            endTime,
            "0",
            "1000"
        )
        println("GET LockMsg url: $url")
        HttpUtil.getAsync(
            url = url.toString(),
        ) { result ->
            result.onSuccess { response ->
                println("GET Alarm Response: $response")
                runOnUiThread {
                    tv_msg.text = response
                }

            }.onFailure { exception ->
                println("GET Error: ${exception.message}")
            }
        }
    }
}